<script setup>
import { ref } from 'vue';
import { useUserStore } from '/src/store/userStore.js';
import { useRouter } from 'vue-router';

const username = ref("");
const password = ref("");
const form1 = ref(null);
const loading = ref(false);
const errorMessage = ref("");

const userStore = useUserStore();
const router = useRouter();

const loginForm = async () => {
  if (!username.value) {
    errorMessage.value = "请输入用户名";
    return;
  }
  if (!password.value) {
    errorMessage.value = "请输入密码";
    return;
  }

  loading.value = true;
  errorMessage.value = "";

  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 验证逻辑（实际项目中应该调用API）
    if (username.value === "admin" && password.value === "123456") {
      const userData = {
        username: username.value,
        gender: '男',
        post: '前端开发工程师',
        sign: 'man!'
      };
      
      userStore.login(userData);
      router.push('/user/person');
    } else {
      throw new Error('用户名或密码错误');
    }
  } catch (error) {
    errorMessage.value = error.message || '登录失败';
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  username.value = "";
  password.value = "";
  errorMessage.value = "";
};
</script>

<template>
  <el-row>
    <el-col :md="24" :lg="8"></el-col>
    <el-col :md="24" :lg="8">
      <h1>登录</h1>
      <el-form ref="form1" style="max-width: 600px" label-width="auto">
        <el-form-item label="用户名">
          <el-input v-model="username" placeholder="username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" type="password" placeholder="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loginForm" :loading="loading">
            登录
          </el-button>
          <el-button @click="resetForm">
            取消
          </el-button>
        </el-form-item>
        <el-alert v-if="errorMessage" :title="errorMessage" type="error" show-icon />
      </el-form>
    </el-col>
    <el-col :md="24" :lg="8"></el-col>
  </el-row>
</template>